<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->

<template>
  <div class="p-6">
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-800">通知管理</h1>
      <p class="text-gray-500 mt-2">自定义您接收的通知类型和通知方式，管理通知历史记录</p>
    </div>

    <!-- 通知偏好设置卡片 -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
      <div class="flex items-center justify-between mb-4">
        <div>
          <h2 class="text-lg font-medium text-gray-800">通知偏好设置</h2>
          <p class="text-sm text-gray-500 mt-1">选择您希望接收的通知类型和通知方式</p>
        </div>
        <el-icon class="text-blue-500 text-2xl"><Setting /></el-icon>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="flex justify-center items-center py-8">
        <el-icon class="animate-spin text-blue-500 text-2xl mr-2"><Loading /></el-icon>
        <span class="text-gray-500">加载中...</span>
      </div>

      <!-- 通知配置内容 -->
      <div v-else-if="notificationTypes.length > 0">
        <div class="mb-6">
          <h3 class="text-md font-medium text-gray-700 mb-3">通知类型</h3>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div
              v-for="(type, index) in notificationTypes"
              :key="index"
              class="flex items-center justify-between p-3 border border-gray-200 rounded-lg"
            >
              <div class="flex items-center">
                <el-icon :class="type.iconClass"><component :is="type.icon" /></el-icon>
                <div class="ml-3">
                  <div class="text-sm font-medium text-gray-800">{{ type.name }}</div>
                  <div class="text-xs text-gray-500">{{ type.description }}</div>
                </div>
              </div>
              <el-switch v-model="type.enabled" />
            </div>
          </div>
        </div>

        <div>
          <h3 class="text-md font-medium text-gray-700 mb-3">通知方式</h3>
          <div class="overflow-x-auto">
            <table class="min-w-full">
              <thead>
                <tr>
                  <th class="text-left text-sm font-medium text-gray-600 pb-3">通知类型</th>
                  <th class="text-center text-sm font-medium text-gray-600 pb-3">站内信</th>
                  <th class="text-center text-sm font-medium text-gray-600 pb-3">邮件</th>
                  <th class="text-center text-sm font-medium text-gray-600 pb-3">短信</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="(type, index) in notificationTypes"
                  :key="index"
                  class="border-t border-gray-100"
                >
                  <td class="py-3">
                    <div class="flex items-center">
                      <el-icon :class="type.iconClass"><component :is="type.icon" /></el-icon>
                      <span class="ml-2 text-sm text-gray-800">{{ type.name }}</span>
                    </div>
                  </td>
                  <td class="py-3 text-center">
                    <el-switch v-model="type.methods.insite" :disabled="!type.enabled" />
                  </td>
                  <td class="py-3 text-center">
                    <el-switch v-model="type.methods.email" :disabled="!type.enabled" />
                  </td>
                  <td class="py-3 text-center">
                    <el-switch v-model="type.methods.sms" :disabled="!type.enabled" />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <div class="mt-6 text-right">
          <button
            @click="saveNotificationSettings"
            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors cursor-pointer whitespace-nowrap !rounded-button"
          >
            <el-icon class="mr-1.5">
              <Check />
            </el-icon>
            保存设置
          </button>
        </div>
      </div>

      <!-- 无数据状态 -->
      <div v-else class="flex flex-col items-center justify-center py-12">
        <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
          <el-icon class="text-gray-400 text-2xl">
            <Bell />
          </el-icon>
        </div>
        <h3 class="text-lg font-medium text-gray-700 mb-2">暂无通知配置</h3>
        <p class="text-gray-500 text-center max-w-md">
          系统正在加载通知配置信息，请稍候再试或联系管理员
        </p>
        <button
          @click="loadNotificationPreference"
          class="mt-4 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
        >
          <el-icon class="mr-1.5">
            <Refresh />
          </el-icon>
          重新加载
        </button>
      </div>
    </div>

    <!-- 通知历史记录卡片 -->
    <div class="bg-white rounded-lg shadow p-6">
      <div class="flex items-center justify-between mb-4">
        <div>
          <h2 class="text-lg font-medium text-gray-800">通知历史记录</h2>
          <p class="text-sm text-gray-500 mt-1">查看您接收到的所有通知</p>
        </div>
        <el-icon class="text-blue-500 text-2xl"><Notification /></el-icon>
      </div>

      <!-- 筛选器 -->
      <div class="bg-gray-50 rounded-xl mb-6 border border-gray-100 overflow-hidden">
        <!-- 筛选器标题栏 -->
        <div 
          class="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-100 transition-colors"
          @click="toggleFilters"
        >
          <div class="flex items-center">
            <el-icon class="text-blue-500 mr-2">
              <List />
            </el-icon>
            <h3 class="text-lg font-semibold text-gray-800">筛选条件</h3>
            <span v-if="hasActiveFilters" class="ml-2 px-2 py-0.5 text-xs bg-blue-100 text-blue-600 rounded-full">
              已应用筛选
            </span>
          </div>
          <div class="flex items-center">
            <span class="text-sm text-gray-500 mr-2">
              {{ filtersExpanded ? '收起' : '展开' }}
            </span>
            <el-icon 
              :class="[
                'text-gray-400 transition-transform duration-200',
                filtersExpanded ? 'rotate-180' : ''
              ]"
            >
              <ArrowDown />
            </el-icon>
          </div>
        </div>

        <!-- 筛选器内容 -->
        <div 
          :class="[
            'transition-all duration-300 ease-in-out',
            filtersExpanded ? 'max-h-96 opacity-100' : 'max-h-0 opacity-0'
          ]"
          style="overflow: hidden;"
        >
          <div class="p-4 pt-0 border-t border-gray-200">
            <!-- 通知类型筛选 -->
            <div class="mb-6">
              <div class="flex items-center mb-3">
                <el-icon class="text-blue-500 mr-2">
                  <Bell />
                </el-icon>
                <h4 class="text-sm font-semibold text-gray-800">通知类型</h4>
              </div>
              <div class="flex flex-wrap gap-3">
                <button
                  :class="[
                    'px-4 py-2 text-sm font-medium rounded-lg transition-all duration-200 shadow-sm',
                    !activeTypeFilter 
                      ? 'bg-blue-100 text-blue-800 border-2 border-blue-300 shadow-blue-100 transform scale-105' 
                      : 'bg-white text-gray-700 hover:text-blue-600 hover:bg-blue-50 hover:shadow-md hover:transform hover:scale-105 border border-gray-200'
                  ]"
                  @click="setTypeFilter(null)"
                >
                  <el-icon class="mr-1.5">
                    <List />
                  </el-icon>
                  全部类型
                </button>
                <button
                  v-for="type in notificationTypes"
                  :key="type.id"
                  :class="[
                    'px-4 py-2 text-sm font-medium rounded-lg transition-all duration-200 shadow-sm flex items-center',
                    activeTypeFilter === type.name
                      ? 'bg-blue-100 text-blue-800 border-2 border-blue-300 shadow-blue-100 transform scale-105'
                      : 'bg-white text-gray-700 hover:text-blue-600 hover:bg-blue-50 hover:shadow-md hover:transform hover:scale-105 border border-gray-200'
                  ]"
                  @click="setTypeFilter(type.name)"
                >
                  <el-icon :class="[activeTypeFilter === type.name ? 'text-blue-700' : type.iconClass, 'mr-1.5']">
                    <component :is="type.icon" />
                  </el-icon>
                  {{ type.name }}
                </button>
              </div>
            </div>

            <!-- 状态筛选 -->
            <div class="mb-6">
              <div class="flex items-center mb-3">
                <el-icon class="text-green-500 mr-2">
                  <CircleCheck />
                </el-icon>
                <h4 class="text-sm font-semibold text-gray-800">阅读状态</h4>
              </div>
              <div class="flex flex-wrap gap-3">
                <button
                  :class="[
                    'px-4 py-2 text-sm font-medium rounded-lg transition-all duration-200 shadow-sm flex items-center',
                    !activeStatusFilter 
                      ? 'bg-gray-200 text-gray-800 border-2 border-gray-300 shadow-gray-100 transform scale-105' 
                      : 'bg-white text-gray-700 hover:text-gray-800 hover:bg-gray-50 hover:shadow-md hover:transform hover:scale-105 border border-gray-200'
                  ]"
                  @click="setStatusFilter(null)"
                >
                  <el-icon class="mr-1.5">
                    <List />
                  </el-icon>
                  全部状态
                </button>
                <button
                  :class="[
                    'px-4 py-2 text-sm font-medium rounded-lg transition-all duration-200 shadow-sm flex items-center',
                    activeStatusFilter === 'unread'
                      ? 'bg-orange-100 text-orange-800 border-2 border-orange-300 shadow-orange-100 transform scale-105'
                      : 'bg-white text-gray-700 hover:text-orange-600 hover:bg-orange-50 hover:shadow-md hover:transform hover:scale-105 border border-gray-200'
                  ]"
                  @click="setStatusFilter('unread')"
                >
                  <div :class="[activeStatusFilter === 'unread' ? 'bg-orange-600' : 'bg-orange-500', 'w-2 h-2 rounded-full mr-2']"></div>
                  未读通知
                </button>
                <button
                  :class="[
                    'px-4 py-2 text-sm font-medium rounded-lg transition-all duration-200 shadow-sm flex items-center',
                    activeStatusFilter === 'read'
                      ? 'bg-green-100 text-green-800 border-2 border-green-300 shadow-green-100 transform scale-105'
                      : 'bg-white text-gray-700 hover:text-green-600 hover:bg-green-50 hover:shadow-md hover:transform hover:scale-105 border border-gray-200'
                  ]"
                  @click="setStatusFilter('read')"
                >
                  <el-icon :class="[activeStatusFilter === 'read' ? 'text-green-700' : 'text-green-500', 'mr-1.5']">
                    <Check />
                  </el-icon>
                  已读通知
                </button>
              </div>
            </div>

            <!-- 日期筛选和操作按钮 -->
            <div class="flex flex-wrap items-center justify-between gap-4 pt-4 border-t border-gray-200">
              <div class="flex items-center gap-3">
                <div class="flex items-center gap-2">
                  <el-icon class="text-purple-500">
                    <Calendar />
                  </el-icon>
                  <span class="text-sm font-medium text-gray-700">时间范围</span>
                </div>
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  size="small"
                  clearable
                  @change="onDateRangeChange"
                />
              </div>
              
              <div class="flex items-center gap-3">
                <button
                  @click="clearAllFilters"
                  class="px-4 py-2 text-sm font-medium bg-gradient-to-r from-gray-400 to-gray-500 text-white rounded-lg hover:from-gray-500 hover:to-gray-600 transition-all duration-200 shadow-sm hover:shadow-md transform hover:scale-105"
                >
                  <el-icon class="mr-1.5">
                    <Refresh />
                  </el-icon>
                  清空筛选
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 批量操作按钮区域 -->
      <div v-if="multipleSelection.length > 0" class="flex items-center justify-between mb-4 p-4 bg-blue-50 rounded-lg border border-blue-200">
        <div class="flex items-center text-sm text-blue-700">
          <el-icon class="mr-2">
            <InfoFilled />
          </el-icon>
          <span>已选中 {{ multipleSelection.length }} 条通知</span>
        </div>
        <div class="flex items-center gap-3">
          <button
            @click="handleBatchRead"
            :disabled="batchReadLoading"
            class="px-4 py-2 text-sm font-medium text-white rounded-lg transition-all duration-200 shadow-sm hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed"
            style="background: linear-gradient(to right, #3b82f6, #2563eb);"
          >
            <el-icon class="mr-1.5" :class="{ 'animate-spin': batchReadLoading }">
              <Loading v-if="batchReadLoading" />
              <Check v-else />
            </el-icon>
            {{ batchReadLoading ? '标记中...' : '标记已读' }}
          </button>
          <button
            @click="handleBatchDelete"
            :disabled="batchDeleteLoading"
            class="px-4 py-2 text-sm font-medium text-white rounded-lg transition-all duration-200 shadow-sm hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed"
            style="background: linear-gradient(to right, #ef4444, #dc2626);"
          >
            <el-icon class="mr-1.5" :class="{ 'animate-spin': batchDeleteLoading }">
              <Loading v-if="batchDeleteLoading" />
              <Delete v-else />
            </el-icon>
            {{ batchDeleteLoading ? '删除中...' : '批量删除' }}
          </button>
        </div>
      </div>

      <!-- 通知列表 -->
      <div class="mb-4">
        <div v-if="noticeLoading" class="flex justify-center items-center py-8">
          <el-icon class="animate-spin text-blue-500 text-2xl mr-2"><Loading /></el-icon>
          <span class="text-gray-500">加载中...</span>
        </div>
        <el-table
          v-else
          ref="multipleTable"
          :data="filteredNotifications"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="状态" width="80">
            <template #default="scope">
              <div class="flex justify-center">
                <span v-if="scope.row.status === 0" class="w-2 h-2 bg-blue-500 rounded-full"></span>
                <span v-else class="text-xs text-gray-400">已读</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="类型" width="120">
            <template #default="scope">
              <div class="flex items-center">
                <el-icon :class="getTypeIcon(scope.row.type).class">
                  <component :is="getTypeIcon(scope.row.type).icon" />
                </el-icon>
                <span class="ml-2 text-sm">{{ scope.row.type }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" width="200">
            <template #default="scope">
              <div class="flex items-center">
                <span :class="{ 'font-medium': scope.row.status === 0 }">{{ scope.row.title }}</span>
                <span
                  v-if="scope.row.important"
                  class="ml-2 px-1.5 py-0.5 text-xs bg-red-100 text-red-600 rounded"
                >重要</span>
                <span
                  v-for="tag in scope.row.tags"
                  :key="tag.tagName"
                  :class="tag.tagStyle || 'bg-gray-100 text-gray-600'"
                  class="ml-1 px-1.5 py-0.5 text-xs rounded"
                >
                  {{ tag.tagName }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="内容">
            <template #default="scope">
              <div class="text-sm text-gray-600">
                <span class="line-clamp-2" :title="scope.row.content">{{ scope.row.content || '暂无内容' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="time" label="时间" width="180" />
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <div class="flex">
                <button
                  v-if="scope.row.status === 0"
                  @click.stop="markAsRead(scope.row)"
                  class="text-blue-500 mr-3 cursor-pointer"
                  title="标记已读"
                >
                  <el-icon><Check /></el-icon>
                </button>
                <button 
                  @click.stop="deleteNotification(scope.row)" 
                  class="text-red-500 cursor-pointer"
                  title="删除"
                >
                  <el-icon><Delete /></el-icon>
                </button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="flex justify-between items-center">
        <div class="text-sm text-gray-500">共 {{ totalNotifications }} 条通知</div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalNotifications"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import {
  User,
  Lock,
  Bell,
  ChatDotRound,
  Picture,
  VideoPlay,
  Medal,
  Star,
  ShoppingCart,
  List,
  Document,
  Upload,
  Setting,
  Notification,
  InfoFilled,
  Check,
  Delete,
  Message,
  Warning,
  WarningFilled,
  CircleCheck,
  Connection,
  CreditCard,
  Promotion,
  Calendar,
  Discount,
  Loading,
  Refresh,
  ArrowDown,
} from '@element-plus/icons-vue'
import { ElMessage, ElLoading } from 'element-plus'
import { useRouter1 } from '../utils/useRoute'
import { 
  getNotificationPreference, 
  updateNotificationPreference,
  getNoticeList,
  batchDeleteNotice,
  batchUpdateNoticeStatus
} from '@/api/user'

const {
  goToHome,
  goToDocumentUpload,
  goToKnowledgeBaseManagement,
  goToMemberCenter,
  goToNotificationSettings,
  goToOrder,
  goToPointsManagement,
  goToSecuritySettings,
  goToUser,
  goToAiChat,
  goToAiDrawing,
  goToProduct,
} = useRouter1()

// 通知方式位运算常量
const NOTIFICATION_METHODS = {
  INSITE: 1,  // 001 站内信
  EMAIL: 2,   // 010 邮件
  SMS: 4      // 100 短信
}

// 通知类型图标映射
const getNotificationTypeIcon = (typeName) => {
  const iconMap = {
    // 系统相关
    '系统通知': { icon: 'Bell', iconClass: 'text-blue-500' },
    '系统维护': { icon: 'Setting', iconClass: 'text-blue-600' },
    '系统更新': { icon: 'Upload', iconClass: 'text-blue-400' },
    
    // 安全相关
    '安全提醒': { icon: 'WarningFilled', iconClass: 'text-red-500' },
    '安全验证': { icon: 'Lock', iconClass: 'text-red-600' },
    '登录异常': { icon: 'Warning', iconClass: 'text-red-400' },
    
    // 活动营销
    '活动推送': { icon: 'Promotion', iconClass: 'text-orange-500' },
    '营销通知': { icon: 'Star', iconClass: 'text-orange-400' },
    '优惠活动': { icon: 'Discount', iconClass: 'text-orange-600' },
    
    // 订单交易
    '订单通知': { icon: 'ShoppingCart', iconClass: 'text-green-500' },
    '支付通知': { icon: 'CreditCard', iconClass: 'text-green-600' },
    '交易提醒': { icon: 'Connection', iconClass: 'text-green-400' },
    
    // 账户相关
    '账户通知': { icon: 'User', iconClass: 'text-purple-500' },
    '积分变动': { icon: 'Medal', iconClass: 'text-purple-400' },
    '余额提醒': { icon: 'CreditCard', iconClass: 'text-purple-600' },
    
    // 服务相关
    '服务到期提醒': { icon: 'Calendar', iconClass: 'text-yellow-500' },
    '会员服务': { icon: 'Star', iconClass: 'text-yellow-400' },
    '套餐通知': { icon: 'Document', iconClass: 'text-yellow-600' },
    
    // 内容相关
    '消息通知': { icon: 'Message', iconClass: 'text-indigo-500' },
    '评论回复': { icon: 'ChatDotRound', iconClass: 'text-indigo-400' },
    '内容更新': { icon: 'Document', iconClass: 'text-indigo-600' },
    
    // AI相关
    'AI服务': { icon: 'Picture', iconClass: 'text-cyan-500' },
    '绘图通知': { icon: 'Picture', iconClass: 'text-cyan-400' },
    '视频通知': { icon: 'VideoPlay', iconClass: 'text-cyan-600' },
  }
  
  // 如果找到精确匹配，返回对应图标
  if (iconMap[typeName]) {
    return iconMap[typeName]
  }
  
  // 关键词匹配回退机制
  const keywordMaps = [
    { keywords: ['系统', '维护', '更新', '升级'], icon: 'Setting', iconClass: 'text-blue-500' },
    { keywords: ['安全', '验证', '登录', '密码'], icon: 'Lock', iconClass: 'text-red-500' },
    { keywords: ['活动', '营销', '推广', '优惠'], icon: 'Promotion', iconClass: 'text-orange-500' },
    { keywords: ['订单', '支付', '交易', '购买'], icon: 'ShoppingCart', iconClass: 'text-green-500' },
    { keywords: ['账户', '用户', '个人', '资料'], icon: 'User', iconClass: 'text-purple-500' },
    { keywords: ['积分', '余额', '钱包', '充值'], icon: 'CreditCard', iconClass: 'text-purple-500' },
    { keywords: ['服务', '会员', '套餐', '到期'], icon: 'Calendar', iconClass: 'text-yellow-500' },
    { keywords: ['消息', '评论', '回复', '聊天'], icon: 'Message', iconClass: 'text-indigo-500' },
    { keywords: ['AI', '智能', '绘图', '视频'], icon: 'Picture', iconClass: 'text-cyan-500' },
  ]
  
  // 根据关键词匹配
  for (const keywordMap of keywordMaps) {
    if (keywordMap.keywords.some(keyword => typeName.includes(keyword))) {
      return { icon: keywordMap.icon, iconClass: keywordMap.iconClass }
    }
  }
  
  // 最终默认图标
  return { icon: 'Bell', iconClass: 'text-gray-500' }
}

// 通知类型数据（从接口获取）
const notificationTypes = ref([])

// 通知历史记录数据（改为从接口获取）
const notifications = ref([])

// 筛选状态
const activeTypeFilter = ref(null)
const activeStatusFilter = ref(null)
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const multipleSelection = ref([])

// 表格ref
const multipleTable = ref(null)

// 加载状态
const loading = ref(false)
const noticeLoading = ref(false)
const batchReadLoading = ref(false)
const batchDeleteLoading = ref(false)

// 总通知数量（从接口返回）
const totalNotifications = ref(0)

// 计算未读通知数量
const unreadCount = computed(() => {
  return notifications.value.filter((item) => item.status === 0).length
})

// 根据筛选条件过滤通知（这里改为直接从接口获取，不需要前端过滤）
const filteredNotifications = computed(() => {
  return notifications.value
})

// 获取通知类型对应的图标
const getTypeIcon = (typeName) => {
  const typeObj = notificationTypes.value.find((item) => item.name === typeName)
  if (typeObj) {
    return {
      icon: typeObj.icon,
      class: typeObj.iconClass,
    }
  }
  return {
    icon: 'Bell',
    class: 'text-gray-500',
  }
}

// 表格多选变化事件
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 分页变化事件
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadNoticeList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadNoticeList()
}

// 筛选操作方法
const setTypeFilter = (typeName) => {
  activeTypeFilter.value = typeName
  currentPage.value = 1
  loadNoticeList()
}

const setStatusFilter = (status) => {
  activeStatusFilter.value = status
  currentPage.value = 1
  loadNoticeList()
}

const onDateRangeChange = () => {
  currentPage.value = 1
  loadNoticeList()
}

const clearAllFilters = () => {
  activeTypeFilter.value = null
  activeStatusFilter.value = null
  dateRange.value = []
  currentPage.value = 1
  loadNoticeList()
}

// 标记为已读
const markAsRead = async (row) => {
  try {
    await batchUpdateNoticeStatus({ ids: [row.id] })
    
    const index = notifications.value.findIndex((item) => item.id === row.id)
    if (index !== -1) {
      notifications.value[index].status = 1 // 0-未读 1-已读
      notifications.value[index].read = true
    }
    
    ElMessage.success('已标记为已读')
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记失败，请重试')
  }
}

// 删除通知
const deleteNotification = async (row) => {
  try {
    await batchDeleteNotice({ ids: [row.id] })
    
    const index = notifications.value.findIndex((item) => item.id === row.id)
    if (index !== -1) {
      notifications.value.splice(index, 1)
      totalNotifications.value = Math.max(0, totalNotifications.value - 1)
    }
    
    ElMessage.success('删除成功')
    
    // 如果当前页没有数据且不是第一页，跳转到上一页
    if (notifications.value.length === 0 && currentPage.value > 1) {
      currentPage.value--
      loadNoticeList()
    }
  } catch (error) {
    console.error('删除通知失败:', error)
    ElMessage.error('删除失败，请重试')
  }
}

// 批量标记已读
const handleBatchRead = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要标记的通知')
    return
  }

  batchReadLoading.value = true
  try {
    const ids = multipleSelection.value.map(item => item.id)
    await batchUpdateNoticeStatus({ ids })
    
    // 更新本地状态
    multipleSelection.value.forEach((selected) => {
      const index = notifications.value.findIndex((item) => item.id === selected.id)
      if (index !== -1 && notifications.value[index].status === 0) {
        notifications.value[index].status = 1
        notifications.value[index].read = true
      }
    })
    
    ElMessage.success(`成功标记 ${ids.length} 条通知为已读`)
    // 清空选择
    multipleSelection.value = []
  } catch (error) {
    console.error('批量标记已读失败:', error)
    ElMessage.error('标记失败，请重试')
  } finally {
    batchReadLoading.value = false
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的通知')
    return
  }

  batchDeleteLoading.value = true
  try {
    const ids = multipleSelection.value.map(item => item.id)
    await batchDeleteNotice({ ids })
    
    // 更新本地状态
    const selectedIds = multipleSelection.value.map((item) => item.id)
    notifications.value = notifications.value.filter((item) => !selectedIds.includes(item.id))
    totalNotifications.value = Math.max(0, totalNotifications.value - selectedIds.length)
    
    ElMessage.success(`成功删除 ${ids.length} 条通知`)
    // 清空选择
    multipleSelection.value = []
    
    // 如果当前页没有数据且不是第一页，跳转到上一页
    if (notifications.value.length === 0 && currentPage.value > 1) {
      currentPage.value--
      loadNoticeList()
    }
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessage.error('删除失败，请重试')
  } finally {
    batchDeleteLoading.value = false
  }
}

// 时间格式化函数
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取通知状态文本
const getStatusText = (status) => {
  return status === 0 ? '未读' : '已读'
}

// 获取通知类型ID（根据类型名称查找）
const getNoticeTypeId = (typeName) => {
  const type = notificationTypes.value.find(item => item.name === typeName)
  return type ? type.id : undefined
}

// 获取通知列表
const loadNoticeList = async () => {
  noticeLoading.value = true
  try {
    // 构建查询参数
    const params = {
      page: {
        page: currentPage.value,
        limit: pageSize.value,
        order: 'DESC',
        field: 'create_time'
      }
    }

    // 添加筛选条件
    if (activeTypeFilter.value) {
      params.noticeTypeId = getNoticeTypeId(activeTypeFilter.value)
    }

    if (activeStatusFilter.value === 'read') {
      params.status = 1
    } else if (activeStatusFilter.value === 'unread') {
      params.status = 0
    }

    // 处理日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      params.startTime = new Date(dateRange.value[0]).getTime()
      params.endTime = new Date(dateRange.value[1]).getTime()
    }

    const response = await getNoticeList(params)
    
    // 转换数据格式以适配现有模板
    notifications.value = response.data.map(item => ({
      id: item.id,
      type: item.noticeTypeName,
      title: item.noticeTitle,
      content: item.noticeContent,
      time: formatTime(item.createTime),
      read: item.status === 1,
      status: item.status,
      tags: item.noticeTags,
      important: item.noticeTags.some(tag => tag.tagName === '重要')
    }))
    
    totalNotifications.value = response.totalCount
  } catch (error) {
    console.error('获取通知列表失败:', error)
    ElMessage.error('获取通知列表失败')
  } finally {
    noticeLoading.value = false
  }
}

// 保存通知配置
const saveNotificationSettings = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '保存中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    // 批量更新所有通知配置
    const updatePromises = notificationTypes.value.map(async (type) => {
      const userPreference = type.enabled ? convertToUserPreference(type.methods) : 0
      
      if (type.id > 0) {
        return await updateNotificationPreference({
          id: type.id,
          userPreference
        })
      }
    })

    await Promise.all(updatePromises.filter(Boolean))
    ElMessage.success('通知设置已保存')
  } catch (error) {
    console.error('保存通知设置失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    loading.close()
  }
}

// 加载通知配置
const loadNotificationPreference = async () => {
  loading.value = true
  try {
    const preferences = await getNotificationPreference()
    
    // 直接使用接口返回的数据构建通知类型列表
    notificationTypes.value = preferences.map((preference) => {
      const iconInfo = getNotificationTypeIcon(preference.noticeTypeName)
      
      return {
        id: preference.id,
        name: preference.noticeTypeName,
        description: preference.noticeTypeDesc,
        icon: iconInfo.icon,
        iconClass: iconInfo.iconClass,
        enabled: preference.userPreference > 0,
        methods: convertToMethods(preference.userPreference)
      }
    })
  } catch (error) {
    console.error('加载通知配置失败:', error)
    ElMessage.error('加载通知配置失败')
  } finally {
    loading.value = false
  }
}

// 位运算工具函数
const convertToMethods = (userPreference) => {
  return {
    insite: (userPreference & NOTIFICATION_METHODS.INSITE) !== 0,
    email: (userPreference & NOTIFICATION_METHODS.EMAIL) !== 0,
    sms: (userPreference & NOTIFICATION_METHODS.SMS) !== 0,
  }
}

const convertToUserPreference = (methods) => {
  let preference = 0
  if (methods.insite) preference |= NOTIFICATION_METHODS.INSITE
  if (methods.email) preference |= NOTIFICATION_METHODS.EMAIL
  if (methods.sms) preference |= NOTIFICATION_METHODS.SMS
  return preference
}

// 页面加载时执行
onMounted(() => {
  loadNotificationPreference()
  loadNoticeList()
})

// 筛选器展开/收起逻辑
const filtersExpanded = ref(false)
const hasActiveFilters = computed(() => {
  return activeTypeFilter.value || activeStatusFilter.value || (dateRange.value && dateRange.value.length > 0)
})
const toggleFilters = () => {
  filtersExpanded.value = !filtersExpanded.value
}

// 处理行点击事件
const handleRowClick = (row) => {
  // 使用表格的toggleRowSelection方法切换选中状态
  if (multipleTable.value) {
    multipleTable.value.toggleRowSelection(row)
  }
}

</script>

<style scoped>
:deep(.el-icon) {
  font-size: 1.25rem;
}

:deep(.el-table .cell) {
  padding: 8px 12px;
}

:deep(.el-pagination) {
  justify-content: flex-end;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f8fafc;
}

input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
